import { Card, Form, Input, Button, Checkbox, message } from "antd";
import logo from "@/assets/images/logo.png";
import styles from "./index.module.scss";
import { login } from "@/store/actions/login";
import { useDispatch } from "react-redux";
import { useState } from "react";

const Login = (props) => {
  // 按钮增加loading状态
  const [loading, setIsloading] = useState(false)
  
  const dispatch = useDispatch();

  const onFinish = (initialValues) => {
    setIsloading(true)
    console.log(initialValues, 77);
    try {
      dispatch(login(initialValues));
      message.success("登录成功", 1, () => {
        // 实现页面跳转
        props.history.push("/layout");
        setIsloading(false)
      });
    } catch (error) {
      message.error("登录失败");
    }
  };
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          autoComplete="on"
          size="large"
          validateTrigger={["onBlur"]}
          initialValues={{
            agree: true,
            mobile: "13696363256",
            code: "246810",
            remember:'checked'
          }}
          onFinish={onFinish}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern:
                  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
                message: "手机号码格式不对",
              },
              { required: true, message: "请输入手机号" }, // 必须要填
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { len: 6, message: "验证码6个字符", validateTrigger: "onBlur" },
              { required: true, message: "请输入验证码" },
            ]}
          >
            <Input size="large" placeholder="请输入验证码" maxLength={6} />
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            rules={[
              {
                validator(rule, value) {
                  if (value) {
                    return Promise.resolve();
                  } else {
                    return Promise.reject(new Error("请阅读并同意协议"));
                  }
                },
              },
            ]}
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意[隐私条款]和[用户协议]
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" loading={loading} htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
